#!/usr/bin/env python2
# coding=utf-8
import threading
import thread
import time
import sqlite3
import sys,os
#sys.path.append(os.getcwd()+'/SqlInject/sqlmap')
from AutoStart import AutoStart
proce = {} #结果缓存字典
url_list = {} #目标缓存字典

class startSqlthread(threading.Thread):
    def __init__(self,url,id):
        threading.Thread.__init__(self)
        self.thread_stop=False
        self.url = url
        self.id = id
    def run(self):
        t = AutoStart('http://127.0.0.1:8775',self.url,self.id)
        get_id = t.run()
        if (get_id):
            proce[self.id] = 1
        else:
            proce[self.id] = 0
    def stop(self):
        self.thread_stop = True

def deinnserst(conn):
    while  1:
        #time.sleep(10)
        #print "等待结果"
        if proce:
            for url_id,status in proce.items(): 
                conn.execute("insert into sql_result (url_id,status)values(?,?)",(int(url_id),status))
                conn.commit()
                del proce[url_id]


    

def dbselect(conn):
    cursor = conn.execute("select url_full,id from get_url")
    print "select....."
    #conn.commit()
    for row in cursor:
        url_list[row[1]] = row[0]


if __name__=='__main__':
    args_str = ["-s","-p","8875"]
    # sqlmapapi.main(args_str)
    os.system("python2 "+os.getcwd()+"/sqlmap/sqlmapapi.py -s -H 127.0.0.1 -p 8875")
    # start = apiStart()
    # start.main(args_str)
    print "python2 "+os.getcwd()+"/SqlInject/sqlmap/sqlmapapi.py -s -H 127.0.0.1 -p 8875"
    time.sleep(10)
    conn = sqlite3.connect('../data/urldata.db',check_same_thread = False)
    #conn = sqlite3.connect('test.db',check_same_thread = False)
    cursor = conn.execute("select url_full,id from get_url")
    try:
       #seth = threading.Thread(target = dbselect,args = (conn,))
       inth = threading.Thread(target = deinnserst,args = (conn,))
    except:
        print "Error!"
    #seth.start()
    inth.start()
    
    for row in cursor:
        while 1:
            if (threading.activeCount() < 20):
                break
        try:
            #print row[0]
            thread1=startSqlthread(row[0],row[1])
            thread1.start()
        except:
            print "Error : unable to start thread"
    while 1:
        print "等待所有操作结束剩余线程数",threading.activeCount()-2
        #print "当前线程数:",threading.activeCount()
        time.sleep(3)
        #deinnserst(conn)
        if (threading.activeCount() <= 2 and not proce ):
            inth.stop()
            break
    conn.close()
    print "扫描结束"

